package com.shiku.mianshi.controller;

import cn.xyz.commons.constants.KConstants;
import cn.xyz.commons.constants.KConstants.PayResultCode;
import cn.xyz.commons.ex.ServiceException;
import cn.xyz.commons.support.Callback;
import cn.xyz.commons.utils.DateUtil;
import cn.xyz.commons.utils.ReqUtil;
import cn.xyz.commons.utils.StringUtil;
import cn.xyz.commons.utils.ThreadUtil;
import cn.xyz.commons.vo.JSONMessage;
import cn.xyz.mianshi.currency.DigitalSymbolManagelmpl;
import cn.xyz.mianshi.model.PageResult;
import cn.xyz.mianshi.service.impl.UserManagerImpl;
import cn.xyz.mianshi.utils.SKBeanUtils;

import cn.xyz.mianshi.vo.Bank;
import cn.xyz.mianshi.vo.ConsumeRecord;
import com.mongodb.DBObject;
import io.swagger.annotations.*;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.bson.types.ObjectId;
import org.springframework.web.bind.annotation.*;


import com.alibaba.fastjson.JSONObject;
import com.mongodb.MongoCommandException;
import com.mongodb.MongoQueryException;


/**
 * 钱包模块接口
 * 
 * @author Administrator
 *
 */
@Api(value="UserWalletController",tags="钱包界面相关")
@RestController
@RequestMapping(value="/wallet",method={RequestMethod.GET,RequestMethod.POST})
public class UserWalletController extends AbstractController {
	
	private  UserManagerImpl getUserManager() {
		return SKBeanUtils.getUserManager();
	}
	private DigitalSymbolManagelmpl getDigitalSymbolManage()
	{
		return SKBeanUtils.getDigitalSymbolManagelmpl();
	}
		@ApiOperation("查询用户名下银行卡")
		@RequestMapping(value = "/querybanklist")
		public JSONMessage QueryUserBankList()
		{
			Integer userId = ReqUtil.getUserId();
			PageResult<Bank> recordInfo = SKBeanUtils.getBankManagerIml().queryUserBankList(userId,1,100);
			return JSONMessage.success(recordInfo);
		}
		@ApiOperation("新增用户银行卡")
		@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query",name = "bankcode",value = "银行卡号",dataType = "String",required = true,defaultValue = ""),
			@ApiImplicitParam(paramType = "query",name = "username",value = "持卡人姓名",dataType = "String",required = true,defaultValue = ""),
			@ApiImplicitParam(paramType = "query",name = "bankname",value = "银行名称",dataType = "String",required = true,defaultValue = ""),
		})
		@RequestMapping(value = "/addbankinfo")
		public JSONMessage AddUserBankInfo(@RequestParam(defaultValue="") String bankcode,@RequestParam(defaultValue="") String username,
				@RequestParam(defaultValue="") String bankname)
		{
			//看是否已经被绑定
			if(SKBeanUtils.getBankManagerIml().isBind(bankcode))
			{
				return JSONMessage.failureByErrCode(KConstants.ResultCode.BankCodeExists);
			}
			Integer userId = ReqUtil.getUserId();
			Bank _bankInfo = new Bank();
			_bankInfo.setBankCode(bankcode);
			_bankInfo.setBankName(bankname);
			_bankInfo.setUserID(userId);
			SKBeanUtils.getBankManagerIml().saveEntity(_bankInfo);
			return JSONMessage.success();
		}
		@ApiOperation("删除用户银行卡")
		@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query",name = "bankid",value = "银行卡id",dataType = "String",required = true,defaultValue = "")
		})
		@RequestMapping(value = "/delbankinfo")
		public JSONMessage DelUserBankInfo(@RequestParam(defaultValue="") String  bankid)
		{
			Integer userId = ReqUtil.getUserId();
			//检查是否是自己的银行卡
			if(!SKBeanUtils.getBankManagerIml().isOwner(userId, bankid))
			{
				return JSONMessage.failureByErrCode(KConstants.ResultCode.notBankOwner);
			}
			SKBeanUtils.getBankManagerIml().deleteById(new ObjectId(bankid));
			return JSONMessage.success();
		}
		@ApiOperation("用户发起提现")
		@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query",name = "bankid",value = "银行卡id",dataType = "String",required = true,defaultValue = ""),
			@ApiImplicitParam(paramType = "query",name = "score",value = "提现金额",dataType = "String",required = true,defaultValue = ""),
			@ApiImplicitParam(paramType = "query",name = "paypsw",value = "支付密码",dataType = "String",required = true,defaultValue = "")
		})
		@RequestMapping(value = "/userwithdrawal")
		public JSONMessage UserWithdrawal(@RequestParam(defaultValue="") String bankid,@RequestParam(defaultValue="") String score,@RequestParam(defaultValue="") String paypsw )
		{
			Integer userId = ReqUtil.getUserId();
			Double _dScore = Double.valueOf(score);
			if(SKBeanUtils.getUserManager().getUserMoeny(userId)< _dScore){
				//余额不足
				return JSONMessage.failureByErrCode(PayResultCode.InsufficientBalance);
			}
			if(!SKBeanUtils.getBankManagerIml().isOwner(userId, bankid))
			{
				//银行卡数据错误
				return JSONMessage.failureByErrCode(KConstants.ResultCode.notBankOwner);
			}
			if(_dScore<0){
				throw new ServiceException(KConstants.PayResultCode.InsufficientBalance);
			}
			if(_dScore<0){
				throw new ServiceException(KConstants.PayResultCode.InsufficientBalance);
			}
			//修改金额
			Double balance = SKBeanUtils.getUserManager().rechargeUserMoeny(userId, _dScore, KConstants.MOENY_REDUCE);
			//开启一个线程 添加一条消费记录
			ThreadUtil.executeInThread((Callback) obj -> {
				String tradeNo=StringUtil.getOutTradeNo();
				//创建充值记录
				ConsumeRecord record=new ConsumeRecord();
				record.setUserId(userId);
			
				record.setTradeNo(tradeNo);
				record.setMoney(_dScore);
				record.setStatus(KConstants.OrderStatus.CREATE);
				record.setType(KConstants.ConsumeType.PUT_RAISE_CASH);
				record.setPayType(KConstants.PayType.BALANCEAY); //余额支付
				record.setDesc("用户提现");
				record.setTime(DateUtil.currentTimeSeconds());
				record.setOperationAmount(_dScore);
				record.setCurrentBalance(balance);
				record.setStatus(KConstants.OrderStatus.END);

				SKBeanUtils.getConsumeRecordManager().save(record);
			});
			return JSONMessage.success(balance);
		}
		@ApiOperation("查询用户数字货币地址")
		@ApiImplicitParams({
				@ApiImplicitParam(paramType = "query",name = "symbol_name",value = "类型",dataType = "String",required = false,defaultValue = "trx"),
				@ApiImplicitParam(paramType = "query",name = "query_name",value = "数字货币名称",dataType = "String",required = false,defaultValue = "trc20_usdt"),
		})
		@RequestMapping(value = "/queryotc")
		public JSONMessage getUserOtcAdder(@RequestParam(defaultValue="trx") String symbol_name,
										   @RequestParam(defaultValue="trc20_usdt") String query_name)
		{
			 Integer userId = ReqUtil.getUserId();
			 String OtcAdder = SKBeanUtils.getDigitalSymbolManagelmpl().getDigitalSymbolInfo(symbol_name,userId);
			 if(null==OtcAdder || OtcAdder.length() == 0 )
			 {
			 	//通过接口获取地址
				OtcAdder = getUserManager().getOtcAdderForServer(userId,symbol_name);
			 }

			HashMap<String, Object> map = new HashMap<>();
			map.put("address",OtcAdder);
			map.put("balance",SKBeanUtils.getDigitalSymbolManagelmpl().getUserMoeny(userId,query_name));
//			map.put("fee",SKBeanUtils.getOtcConfig().getFee());
//			map.put("minWithdrawNum",SKBeanUtils.getOtcConfig().getMinWithdrawNum());

			getDigitalSymbolManage().addDigitalSymbolInfo(symbol_name,OtcAdder,userId);
			//插入数字货币
			getDigitalSymbolManage().addDigitalSymbolBalance(query_name,OtcAdder,userId);
			return JSONMessage.success(map);
		}

		@ApiOperation("接口数字货币地址")
		@RequestMapping(value = "/otcnotify")
		public JSONMessage  otcNotify(HttpServletRequest request,HttpServletResponse response)
		{
			String _postValue = "";
			try {
				_postValue = getRequestPostStr(request);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			_postValue = _postValue.replace("\\","");
			if(_postValue.substring(0,1).equals("\""))
			{
				_postValue = _postValue.substring(1,_postValue.length()-1);
			}

				logger.info("[ww]=otcNotify=_postValue="+_postValue);
			JSONObject jsonObject = JSONObject.parseObject(_postValue);
			getUserManager().onOtcNotify(jsonObject);

			JSONMessage _return = new JSONMessage();
			_return.put("error",0);
			_return.put("msg","success");
			return _return;
		}
		@ApiOperation("数字货币提现")
		@ApiImplicitParams({
				@ApiImplicitParam(paramType = "query",name = "otcadder",value = "对方地址",dataType = "String",required = true,defaultValue = ""),
				@ApiImplicitParam(paramType = "query",name = "score",value = "提现金额",dataType = "String",required = true,defaultValue = ""),
				@ApiImplicitParam(paramType = "query",name = "paypsw",value = "支付密码",dataType = "String",required = true,defaultValue = ""),
				@ApiImplicitParam(paramType = "query",name = "SymbolName",value = "类型",dataType = "String",required = true,defaultValue = "trc20_usdt")
		})
		@RequestMapping(value = "/otcwithdraw")
		public JSONMessage otcWithdraw(@RequestParam(defaultValue="") String otcadder,
									   @RequestParam(defaultValue="") String score,
									   @RequestParam(defaultValue="") String paypsw,
									   @RequestParam(defaultValue="erc20_usdt") String SymbolName)
		{
			Integer userId = ReqUtil.getUserId();
		  int bStatus =	getUserManager().onOtcWithdraw(userId,otcadder,score,SymbolName);
		  if(bStatus == 0)
		  {
			return   JSONMessage.success();
		  }
			return   JSONMessage.failureByErrCode(PayResultCode.WithdrawFailure);
		}
		@ApiOperation("数字货币转换")
		@ApiImplicitParams({
				@ApiImplicitParam(paramType = "query",name = "srcSymbol",value = "需要转换的数字货币",dataType = "String",required = true,defaultValue = ""),
				@ApiImplicitParam(paramType = "query",name = "tagSymbol",value = "转换后的数字货币",dataType = "String",required = true,defaultValue = ""),
				@ApiImplicitParam(paramType = "query",name = "score",value = "转换金额",dataType = "String",required = true,defaultValue = ""),
		})
		@RequestMapping(value = "/convert")
		public JSONMessage digitalConvert(
				@RequestParam(defaultValue="") String srcSymbol,
				@RequestParam(defaultValue="") String tagSymbol,
				@RequestParam(defaultValue="0") String score)
		{
			Integer userId = ReqUtil.getUserId();
			Double dbScore = Double.parseDouble(score);
			boolean bStatus =	getDigitalSymbolManage().onDigitalConvert(userId,srcSymbol,tagSymbol,dbScore);
			if(!bStatus)
			{
				return JSONMessage.failure("Convert Failure");
			}
			return   JSONMessage.success();
		}
		@ApiOperation("数字货币转换记录")
		@ApiImplicitParams({
				@ApiImplicitParam(paramType = "query",name = "pageIndex",value = "当前页码",dataType = "int",required = false,defaultValue = "0"),
				@ApiImplicitParam(paramType = "query",name = "pageSize",value = "每页条数",dataType = "int",required = false,defaultValue = "10"),
				@ApiImplicitParam(paramType = "query",name = "srcSymbol",value = "源类型",dataType = "String",required = false,defaultValue = ""),
				@ApiImplicitParam(paramType = "query",name = "tagSymbol",value = "目标源类型",dataType = "String",required = false,defaultValue = ""),
				@ApiImplicitParam(paramType = "query",name = "startTime",value = "开始查询时间",dataType = "int",required = false,defaultValue = "-1"),
				@ApiImplicitParam(paramType = "query",name = "endTime",value = "截至查询时间",dataType = "int",required = false,defaultValue = "-1"),
		})
		@RequestMapping(value = "/convertlist")
	 	public JSONMessage DigitalConvertRecord(@RequestParam(defaultValue="0")int pageIndex,@RequestParam(defaultValue="10")int pageSize,
												 @RequestParam(defaultValue="")String srcSymbol, @RequestParam(defaultValue="")String tagSymbol,
												 @RequestParam(defaultValue="-1")int startTime, @RequestParam(defaultValue="-1")int endTime )
		{
			Integer userId = ReqUtil.getUserId();
			PageResult<DBObject> result =getDigitalSymbolManage().getDigitalConvertRecord(userId,pageIndex,pageSize,srcSymbol,tagSymbol,startTime,endTime);
			return JSONMessage.success(result);
		}
		public  String getRequestPostStr(HttpServletRequest request) throws IOException {
	        byte buffer[] = getRequestPostBytes(request);
	        String charEncoding = request.getCharacterEncoding();
	        if (charEncoding == null) {
	            charEncoding = "UTF-8";
	        }
	        return new String(buffer, charEncoding);
	    }
		 public  byte[] getRequestPostBytes(HttpServletRequest request) throws IOException {
			 logger.info("==getRequestPostBytes==");
		        int contentLength = request.getContentLength();
			 logger.info("==getRequestPostBytes=contentLength="+contentLength);
		        if(contentLength<0){
		            return null;
		        }
		        byte buffer[] = new byte[contentLength];
		        for (int i = 0; i < contentLength;) {
		 
		            int readlen = request.getInputStream().read(buffer, i,
		                    contentLength - i);
		            if (readlen == -1) {
		                break;
		            }
		            i += readlen;
		        }
		        return buffer;
		  }
}
